import Taro from '@tarojs/taro'
import { useReducer, useState } from 'react'
import {  View } from '@tarojs/components'

import PayChannelOption from '../pay-channel'

import './index.scss'
import { useReady, useRouter } from '@tarojs/taro'
import { getDeviceStrategyApi } from '../../../services/Device'
import { addChargeApi, queryAddChargeStatusApi } from '../../../services/Charge'
import { hideLoading, reducer, showLoading, showModal, showToast } from '../../../utils'
import Bluetooth from '../Bluetooth'
import GlobalData from '../../../global'
import ChargeHeader from '../chargeHeader'
import ChargeStrategyOption from '../chargeStrategyOption'
import { Logger } from '../../../Logger'


export default () => {
    const query = useRouter().params
    const deviceId = Number(query.deviceId || 0)
    const orderId = Number(query.orderId || 0)


    const [formData, formDataDispatch] = useReducer(reducer, {
        chargeQuantity : '',
    })

    let [queryOrderStatusCount, setqueryOrderStatusCount] = useState(0) //查询充电订单状态次数
    let [deviceConnectStatus, setdeviceConnectStatus] = useState(true)
    let [strategy, setstrategy] = useState<Strategy>()


    async function charge() {
        //Bluetooth.openBluetoothAdapter()

        //return

        if(formData.chargeQuantity === '') {
            showToast('请选择充电金额')
            return
        }

        setqueryOrderStatusCount(0)

        showLoading('请求中')
        let result = await addChargeApi(orderId, formData.chargeQuantity)
        if(!result.success) {
            hideLoading()
            showModal(result.msg)
            return
        }

        queryOrderStatus(result.data)
    }

    function queryOrderStatus(addOrderId:number) {
        setTimeout(async () => {
            queryOrderStatusCount += 1
            setqueryOrderStatusCount(queryOrderStatusCount)
            let res = await queryAddChargeStatusApi(addOrderId)
            if(res.success) {
                let status = Number(res.data)
                if(status == 0) { //继续查询
                    if(queryOrderStatusCount > 5) {
                        hideLoading()
                        showModal('充电失败，费用稍后将退回')
                        return
                    }
                    //继续查询
                    queryOrderStatus(orderId)
                }else if(status == 1) {//充电成功
                    hideLoading()
                    Taro.navigateBack()
                }else if(status == 2) {
                    hideLoading()
                    showModal('充电失败，费用稍后将退回')
                }
                
            }else {
                hideLoading()
            }
        }, 5000);
        
    }


    useReady(async () => {
        showLoading()
        let strategy = await getDeviceStrategyApi(deviceId)
        hideLoading()
        if(strategy) {
            setstrategy(strategy)
        }
        
    })

    return (
        <>
            <View className='page-view'>
                {deviceConnectStatus == false &&
                    <View className='device-offline'>设备已掉线，请开启蓝牙充电</View>
                }
                
                <View className='flex-1' style='overflow-y:auto'>
                    <>
                        <ChargeHeader strategy={strategy} />
                        
                        <View className='blank m-t-30'></View>
                        <View className='p-l-r m-t-30'>
                            <View className='f-32'>选择充电金额</View>
                            {strategy &&
                                <View className='m-t-20'>
                                    <ChargeStrategyOption options={strategy.options} price={strategy.unitPrice} onChange={e => formDataDispatch({chargeQuantity : e})}></ChargeStrategyOption>
                                </View>
                            }
                        </View>

                        <View className='blank m-t-30'></View>
                        <View className='p-l-r m-t-30'>
                            <View className='f-32'>支付方式：</View>
                            <View className='m-t-10'>
                                <PayChannelOption onChange={() => {}}></PayChannelOption>
                            </View>
                        </View>
                    </>
                </View>

                <View className='footer-nav'>
                    <View className='amount font-bold p-l'>需支付：{formData.chargeQuantity || 0}元</View>
                    <View className='confirm-button' onClick={charge}>{deviceConnectStatus ? '立即充电' : '开启蓝牙充电'}</View>
                </View>

            </View>
        </>
    )
}